package com.topone.controller;

import com.topone.Converter.ConvenientInfoForm2ConvenientInfo;
import com.topone.Enum.ConvenientInfoEnum;
import com.topone.Enum.ResultEnum;
import com.topone.Exception.FanZoneException;
import com.topone.Form.ConvenientInfoForm;
import com.topone.Utils.KeyUntil;
import com.topone.Utils.ResultVOUntil;
import com.topone.VO.ResultVO;
import com.topone.config.UploadConfig;
import com.topone.dataObject.ConvenientInfo;
import com.topone.service.ConvenientInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import sun.rmi.server.MarshalOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import javax.validation.Valid;
import java.io.*;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Administrator on 2018/1/1,0001.
 */
@RestController
@CrossOrigin
@Slf4j
@RequestMapping("/buyer/convenientInfo")
public class BuyerConvenientInfoController {
    @Autowired
    private ConvenientInfoService service;

    @Autowired
    private UploadConfig uploadConfig;

    @PostMapping("/save")
    @Transactional
    public ModelAndView save(@Valid ConvenientInfoForm convenientInfoForm,
                                             MultipartHttpServletRequest multiReq,
                                             BindingResult bindingResult,
                                             Map<String,Object> map){
        if(bindingResult.hasErrors()){
            log.error("【便民信息】参数不正确,bussinessInfoForm={}",convenientInfoForm);
            throw new FanZoneException(ResultEnum.CONVENIENT_PARAM_ERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
         //处理上传文件
        // 获取上传文件的路径
        String uploadFilePath = uploadConfig.getFilePath();
        // 截取上传文件的文件名
        String uploadFileName = UUID.randomUUID().toString()
                .replace("-","");
        ///截取上传文件的后缀
        String originalName=multiReq.getFile("file").getOriginalFilename();
        String fileType=originalName
                .substring(originalName.indexOf('.') + 1, originalName.length());
         //文件全路径
        String filePath=uploadFilePath+uploadFileName+"."+fileType;
        FileOutputStream fos=null;
        FileInputStream fis=null;
        try {
            File file = new File(uploadFilePath);
            if(!file.exists()){   //上传路径不存在，创建路径
                file.mkdirs();
            }
             fis=(FileInputStream) multiReq.getFile("file").getInputStream();
            fos = new FileOutputStream(new File(filePath));
            long size=fis.available();
            if(size>104865760){  //上传最大限制10M
                map.put("error","上传文件过大");
                return  new ModelAndView("/buyer/addService",map);
            }

            byte[] data=new byte[fis.available()];
            fis.read(data);
            fos.write(data);
        }catch (IOException e){
            log.error("【添加便民信息】失败, ={}",e);
            e.printStackTrace();
        }finally {
            try {
                if(fis!=null) {
                    fis.close();
                }
                if (fos!=null) {
                    fos.close();
                }
            }catch (IOException e){
                log.error("【添加便民信息】失败",e);
                e.printStackTrace();
            }
        }

        ConvenientInfo convenientInfo= ConvenientInfoForm2ConvenientInfo
                .convert(convenientInfoForm);

        //生成id
        convenientInfo.setConvenientId(KeyUntil.getUniqueKey());
        convenientInfo.setConvenientIcon(filePath);
        //提交订单 默认为待审核
        convenientInfo.setConvenientStatus(ConvenientInfoEnum.CHECK.getCode());
        ConvenientInfo result=new ConvenientInfo();
        try {
            result=service.save(convenientInfo);
        }catch (FanZoneException e){
          log.error("【便民信息上传】申请保存失败!",e.getMessage());
          return  new ModelAndView("/buyer/wx_index",map);
        }
        return new ModelAndView("/buyer/wx_index",map);
    }

    @GetMapping("/list")
    public ResultVO<Map<String,Object>> convientInfo(Map<String,Object> map){
        try {
            List<ConvenientInfo> convenientInfoList=service
                    .findUpAll(ConvenientInfoEnum.ON.getCode());
            map.put("convenientInfoList",convenientInfoList);
        }catch (FanZoneException e){
            log.error("【查询便民信息】e={}",e.getMessage());
            map.put("error",e.getMessage());
            return ResultVOUntil.error(1,e.getMessage());
        }
       log.info("【查询便民信息】成功,{}",map);
        map.put("suceess","查询成功");
        return ResultVOUntil.success(map);
    }

}
